<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
*/
//category function
function addNewCategory() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmNewsAddCategory'])) {
        $data = array();
        if($_POST['cat_title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        $data['cat_title'] = $_POST['cat_title'];
        $data['cat_parent'] = $_POST['cat_parent'];
        $data['cat_link'] = create_link($_POST['cat_title']);
        $data['cat_link'] = checkCatLinkExist($data['cat_link']);
        $data['cat_description'] = $_POST['cat_description'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['cat_active'] = $_POST['cat_active'];
        $data['user_id'] = $_SESSION['adlogin']["id"];
        $data['lang'] = $_SESSION['adlang'];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $bigestOrder = getBigestOrder();
            $data['cat_order'] = $bigestOrder+1;
            $db->exec_insert('cat_projects', $data);
            $CONFIG["success_message"] = "<li>Thêm mới danh mục thành công!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}

function editUpdateCategory() {
    global $db,$CONFIG;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        if(isset($_POST['submitFrmNewsAddCategory'])) {//update category
            $data = array();
            if($_POST['cat_title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            $data['cat_title'] = $_POST['cat_title'];
            $data['cat_parent'] = $_POST['cat_parent'];
            $data['cat_link'] = create_link($_POST['cat_title']);
            $data['cat_description'] = filter($_POST['cat_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['cat_active'] = filter($_POST['cat_active']);
            $data['user_id'] = $_SESSION['adlogin']["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('cat_projects', $data, " cat_id=$cat_id ");
                $CONFIG["success_message"] = "<li>Cập nhật danh mục thành công!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM cat_projects WHERE cat_id=$cat_id");
    }
}

function deleteNewsCat() {
    global $db;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        $arrChildCatNews = getCatNewsIdToArray($cat_id,$trees=null);
        for($i=0;$i<count($arrChildCatNews);$i++) {
            if(intval($arrChildCatNews[$i])>0) {
                $db->exec_delete('cat_projects',"cat_id=".$arrChildCatNews[$i]);
            }
        }
        $db->exec_delete('cat_projects',"cat_id=$cat_id");
    }
}

function getCatNewsIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT cat_id FROM cat_projects WHERE  cat_parent = ".intval($parent_id));
    if($rsCat) {
        while($rs = $db->fetch_array($rsCat)) {
            $trees[] = $rs['cat_id'];
            $trees = getCatNewsIdToArray($rs['cat_id'],$trees);
        }
    }
    return $trees;
}

function listAllNewsCategory($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_projects WHERE  cat_parent = ".intval($parent_id)."  AND lang='".$_SESSION['adlang']."' ORDER BY cat_order");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllNewsCategory($rs['cat_id'],$space.'----',$trees);
    }
    return $trees;
}

function listAllPropertyGeographicByParent($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM geographic WHERE  geo_parent = ".intval($parent_id)." ORDER BY geo_order,geo_id");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['geo_parent']==0) {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$space.$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }
    }
    return $trees;
}

function multiActionCategoryNews() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_cat_id'];
        switch($_REQUEST['formNewsCategoryViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('cat_news','cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }case
            "setStatusYes": {
                        for($i=0;$i<count($arrCatId);$i++) {
                            if(intval($arrCatId[$i])>0) {
                                $db->exec_update('cat_news',array("cat_active"=>'yes'),'cat_id='.intval($arrCatId[$i]));
                            }
                        }
                        break;
                    }case
            "setStatusNo": {
                            for($i=0;$i<count($arrCatId);$i++) {
                                if(intval($arrCatId[$i])>0) {
                                    $db->exec_update('cat_news',array("cat_active"=>'no'),'cat_id='.intval($arrCatId[$i]));
                                }
                            }
                            break;
                        }
                    }
                }
            }

            //order category
            function orderNewsCategory() {
                global $db,$CONFIG,$option;
                if(isset($_POST['submitFrmNewsOrder']) && $_POST['submitFrmNewsOrder']=="Submit") {//update
                    $arrNewsCatID = $_POST['news_order'];
                    if(count($arrNewsCatID)) {
                        for($i=0;$i<count($arrNewsCatID);$i++) {
                            if(intval($arrNewsCatID[$i])>0) {
                                $db->exec_update('cat_news',array("cat_order"=>$i),'cat_id='.intval($arrNewsCatID[$i]));
                            }
                        }
                        if($_POST['submitType']=='exit') {
                            server_redirect(SITE_URL.get_string_url(array('action')));
                        }else {
                            return listAllNewsCategory();
                        }
                    }else {
                        return listAllNewsCategory();
                    }
                }else {//show
                    return listAllNewsCategory();
                }

            }

            // Le Trong Phuc
            //end category function
            //news
            //Uporder category function
            function upOrderNewsCategory() {
                global $db;
                $cat_id = $_REQUEST['cat_id'];

                $arr_cat_order = getOrder($cat_id);
                $cat_order = $arr_cat_order['cat_order'];
                $cat_parent = $arr_cat_order['cat_parent'];

                $arrCatUp = getUpOrder($cat_order,$cat_parent);
                $catUpId = $arrCatUp['cat_id'];
                $catUpOrder = $arrCatUp['cat_order'];
                $data = array();
                $data['cat_order'] = $cat_order;
                $dataUp = array();
                $dataUp['cat_order'] = $catUpOrder;
                //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
                if(intval($catUpId>0)) {
                    $db->query("update cat_projects set cat_order=$catUpOrder where cat_id=$cat_id");
                    $db->query("update cat_projects set cat_order=$cat_order where cat_id=$catUpId");
                }
            }
            function getOrder($cat_id) {
                global $db;
                $rsCat = $db->query_first("SELECT cat_order,cat_parent FROM cat_projects WHERE  cat_id = ".intval($cat_id));
                return $rsCat;
            }
            function getUpOrder($cat_order,$cat_parent) {
                global $db;
                $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_projects WHERE  cat_order<$cat_order AND cat_parent=$cat_parent ORDER BY cat_order DESC");
                return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
            }
            function downOrderNewsCategory() {
                global $db;
                $cat_id = $_REQUEST['cat_id'];

                $arr_cat_order = getOrder($cat_id);
                $cat_order = $arr_cat_order['cat_order'];
                $cat_parent = $arr_cat_order['cat_parent'];
                $arrCatDown = getDownOrder($cat_order,$cat_parent);
                $catDownId = $arrCatDown['cat_id'];
                $catDownOrder = $arrCatDown['cat_order'];
                $data = array();
                $data['cat_order'] = $cat_order;


                $dataUp = array();
                $dataUp['cat_order'] = $catDownOrder;
                //$db->exec_update('cat_news', $dataUp, " cat_id=$catUpId");
                if(intval($catDownId)>0) {
                    $db->query("update cat_projects set cat_order=$catDownOrder where cat_id=$cat_id");
                    $db->query("update cat_projects set cat_order=$cat_order where cat_id=$catDownId");
                }


            }
            function getDownOrder($cat_order,$cat_parent) {
                global $db;
                $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_projects WHERE  cat_order>$cat_order AND cat_parent=$cat_parent ORDER BY cat_order ASC");
                return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
            }

            function getBigestOrder() {
                global $db;
                $rsCat = $db->query_first("SELECT cat_order FROM cat_projects ORDER BY cat_order DESC");
                return $rsCat['cat_order'];
            }
            // End Le Trong Phuc
            //end category function
            //news
            function addNewNews() {
                global $db,$CONFIG;
                if(isset($_POST['submitFrmNewsAdd'])) {
                    $data = array();
                    if($_POST['title']=='') {
                        $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
                    }
                    if(intval($_POST['geo_id'])==0) {
                        $CONFIG["error_message"] .= "<li>Bạn chưa nhập thành phố!</li>";
                    }
                    if($_POST['description']=='') {
                        $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả!</li>";
                    }
                    if($_POST['content']=='') {
                        $CONFIG["error_message"] .= "<li>Bạn chưa nhập nội dung!</li>";
                    }
                    $data['title'] = $_POST['title'];
                    $data['title_link'] = create_link($_POST['title']);
                    $data['title_link'] = checkNewsLinkExist($data['title_link']);
                    $data['cat_id'] = $_POST['cat_id'];
                    $data['geo_id'] = $_POST['geo_id'];
                    $data['map'] = $_POST['map'];
                    $thumb = $_POST['thumb'];
                    $data['thumb'] = $thumb[0];
                    $data['description'] = $_POST['description'];
                    $data['content'] = $_POST['content'];
                    $data['chudautu'] = $_POST['chudautu'];
                    $data['donvituvan'] = $_POST['donvituvan'];
                    $data['donvithicong'] = $_POST['donvithicong'];
                    $data['tongdautu'] = $_POST['tongdautu'];
                    $data['dientich'] = $_POST['dientich'];
                    $data['lang'] = $_SESSION['adlang'];
                    $data['ngaykhoicong'] = date('Y-m-d H:i:s');
                    $data['ngayhoanthanh'] = date('Y-m-d H:i:s');
                    $data['create_date'] = date('Y-m-d H:i:s');



                    if($CONFIG["error_message"]=='') {
                        unset ($_REQUEST);
                        $db->exec_insert('projects', $data);
                        $newsId = mysql_insert_id();
                        //insert data to tags
                        for($i=0;$i<count($thumb);$i++) {
                            if($thumb[$i]!='') {
                                $db->query("INSERT INTO projects_image (project_id, image) VALUES ('$newsId', '$thumb[$i]')");
                            }
                        }
                        if($_POST['submitType']=='exit') {
                            //server_redirect(ADMIN_URL . '?module=news');
                            server_redirect(SITE_URL . get_string_url(array('action')));
                        }
                        $CONFIG["success_message"] = "<li>Thêm mới dự án thành công!</li>";
                    }

                }
            }

            function checkNewsLinkExist($newsLink) {
                global $db;
                $rs = $db->query_first("SELECT id,title_link FROM projects WHERE title_link='$newsLink'");
                if(intval($rs['id'])>0) {
                    $newsLink = $rs['title_link'].'-'.rand(0,9);
                    checkNewsLinkExist($newsLink);
                }
                return $newsLink;
            }

            function checkCatLinkExist($newsCatLink) {
                global $db;
                $rs = $db->query_first("SELECT cat_id,cat_link FROM cat_projects WHERE cat_link='$newsCatLink'");
                if(intval($rs['cat_id'])>0) {
                    $newsCatLink = $rs['cat_link'].'-'.rand(0,9);
                    checkCatLinkExist($newsCatLink);
                }
                return $newsCatLink;
            }

            function checkTagExist($tag) {
                global $db;
                $rs = $db->query_first("SELECT id FROM tags_news WHERE tags='$tag'");
                if($rs) {
                    return $rs['id'];
                }else {
                    return 'donthave';
                }
            }

            function editUpdateNews() {
                global $db,$CONFIG;
                $id = intval($_REQUEST['id']);
                if($id>0) {
                    if(isset($_POST['submitFrmNewsAdd'])) {//update category
                        $data = array();
                        if($_POST['title']=='') {
                            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
                        }
                        if(intval($_POST['geo_id'])==0) {
                            $CONFIG["error_message"] .= "<li>Bạn chưa nhập thành phố</li>";
                        }
                        if($_POST['description']=='') {
                            $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả!</li>";
                        }
                        if($_POST['content']=='') {
                            $CONFIG["error_message"] .= "<li>Bạn chưa nhập nội dung!</li>";
                        }
                        $data['title'] = $_POST['title'];
                        $data['title_link'] = create_link($_POST['title']);
                        $data['title_link'] = checkNewsLinkExist($data['title_link']);
                        $data['cat_id'] = $_POST['cat_id'];
                        $data['geo_id'] = $_POST['geo_id'];
                        $data['map'] = $_POST['map'];
                        $thumb = $_POST['thumb'];
                        $removeThumb = $_POST['removeThumb'];
                        $data['thumb'] = $thumb[0];
                        $data['description'] = $_POST['description'];
                        $data['content'] = $_POST['content'];
                        $data['chudautu'] = $_POST['chudautu'];
                        $data['donvituvan'] = $_POST['donvituvan'];
                        $data['donvithicong'] = $_POST['donvithicong'];
                        $data['tongdautu'] = $_POST['tongdautu'];
                        $data['dientich'] = $_POST['dientich'];
                        $data['ngaykhoicong'] = date('Y-m-d H:i:s');
                        $data['ngayhoanthanh'] = date('Y-m-d H:i:s');
                        //$data['create_date'] = date('Y-m-d H:i:s');

                        if($CONFIG["error_message"]=='') {
                            $db->exec_update('projects', $data, " id=$id ");
                            $CONFIG["success_message"] = "<li>Cập nhật dự án thành công!</li>";
                            //delete images had been removed
                            for($i=0;$i<count($removeThumb);$i++) {
                                if($removeThumb[$i]!='') {
                                    $db->query("DELETE FROM projects_image WHERE id = ".intval($removeThumb[$i]));
                                }
                            }
                            for($i=0;$i<count($thumb);$i++) {
                                if($thumb[$i]!='') {
                                    $db->query("INSERT INTO projects_image (project_id, image) VALUES ('$newsId', '$thumb[$i]')");
                                }
                            }

                            if($_POST['submitType']=='exit') {
                                server_redirect(SITE_URL . get_string_url(array('action','id')));
                            }
                        }
                    }
                    $rsNewsEdit = $db->query_first("SELECT * FROM projects WHERE id=$id");
                    $rsProjectsImage = $db->query("SELECT * FROM projects_image WHERE project_id=".intval($id));
                    return array("rsNewsEdit"=>$rsNewsEdit,"rsProjectsImage"=>$rsProjectsImage);
                }else {
                    server_redirect(SITE_URL . get_string_url(array('action','id')));
                }

            }

            function newsDetail() {
                global $db;
                $id = intval($_REQUEST['id']);
                if($id>0) {
                    return $db->query_first("SELECT * FROM projects WHERE id=$id");
                }else {
                    server_redirect(ADMIN_URL.'?module=projects');
                }
            }

            function deleteNews() {
                global $db;
                $id = intval($_REQUEST['id']);
                if($id>0) {
                    $db->exec_delete('projects',"id=$id");
                }
            }

            function listAllNews() {
                global $db,$CONFIG;
                if(intval($_REQUEST['page'])>0) {
                    $page = $_REQUEST['page'];
                }else {
                    $page = 1;
                }
                // neu' bam vao nut tim kiem
                
				if($_REQUEST['keyword']!='') {
					$searchCondition = ' AND (n.title LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.description LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.content LIKE \'%'.$_REQUEST['keyword'].'%\')';
				}
				if(intval($_REQUEST['cat_id'])>0) {
					$arrCatId = getCatNewsIdToArray($_REQUEST['cat_id']);
					array_push($arrCatId,$_REQUEST['cat_id']);
					if(count($arrCatId)>0) {
						$strCatId = implode(',', $arrCatId);
						$searchCondition .= " AND c.cat_id IN ($strCatId)";
					}else {
						$searchCondition .= " AND c.cat_id =".$_REQUEST['cat_id'];
					}
				}
				//echo $searchCondition;
				$rsNews = $db->query("SELECT n.id FROM projects n LEFT JOIN cat_projects c ON n.cat_id = c.cat_id WHERE 1 $searchCondition  AND n.lang='".$_SESSION['adlang']."' ORDER BY n.create_date DESC");
				$totalRows =  $db->num_rows($rsNews);
				$totalPages = ceil($totalRows/$CONFIG ['rows_per_page_news']);
				$start = (($page*$CONFIG ['rows_per_page_news'])-$CONFIG ['rows_per_page_news']);
				$limit = $CONFIG ['rows_per_page_news'];

				$rs = $db->query("SELECT n.id,n.cat_id,n.title,n.title_link,n.description,n.content,n.active,n.create_date,c.cat_title
						FROM projects n LEFT JOIN cat_projects c ON n.cat_id = c.cat_id
						WHERE 1 $searchCondition  AND n.lang='".$_SESSION['adlang']."' ORDER BY n.create_date DESC LIMIT $start,$limit");
				//chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
				if($db->num_rows($rs)<1) {
					$page = $page - 1;
					if($page>1) {
						server_redirect(get_string_url()."&page=".$page);
					}

				}
				return array(
					"rs"=>$rs,
					"page"=>$page,
					"totalPages"=>$totalPages
				);
                
            }

            function multiActionNews() {
                global $db;
                if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
                    $arrNewsId = $_REQUEST['arr_news_id'];
                    switch($_REQUEST['formNewsViewAction']) {
                        case "delete": {
                                for($i=0;$i<count($arrNewsId);$i++) {
                                    if(intval($arrNewsId[$i])>0) {
                                        $db->exec_delete('projects','id='.intval($arrNewsId[$i]));
                                        $db->exec_delete('projects_image','id='.intval($arrNewsId[$i]));
                                    }
                                }
                                break;
                }case
            "setStatusYes": {
                        for($i=0;$i<count($arrNewsId);$i++) {
                            if(intval($arrNewsId[$i])>0) {
                                $db->exec_update('projects',array("active"=>'yes'),'id='.intval($arrNewsId[$i]));
                            }
                        }
                        break;
                }case
            "setStatusPending": {
                        for($i=0;$i<count($arrNewsId);$i++) {
                            if(intval($arrNewsId[$i])>0) {
                                $db->exec_update('projects',array("active"=>'pending'),'id='.intval($arrNewsId[$i]));
                            }
                        }
                        break;
                    }case
            "setStatusNo": {
                            for($i=0;$i<count($arrNewsId);$i++) {
                                if(intval($arrNewsId[$i])>0) {
                                    $db->exec_update('projects',array("active"=>'no'),'id='.intval($arrNewsId[$i]));
                                }
                            }
                            break;
                        }
                    }
                }
            }

            function getAllCity() {
                global $db;
                $sql="SELECT geo_id,geo_title FROM geographic WHERE geo_link IN ('ha-noi','tp-ho-chi-minh','da-nang') AND (geo_parent=1 OR geo_parent=2 OR geo_parent=3)
          UNION
          SELECT p.* FROM (SELECT geo_id,geo_title FROM  geographic WHERE  geo_link NOT IN ('ha-noi','tp-ho-chi-minh','da-nang') AND (geo_parent=1 OR geo_parent=2 OR geo_parent=3) ORDER BY  geo_title ASC) AS p";
                return $db->query($sql);
            }

            function getProjectsGeographicGrandParent($geo_id) {
                global $db;
                if(intval($geo_id)>0) {
                    return $rs1 = $db->query_first("SELECT geo_parent FROM geographic WHERE  geo_id = ".intval($geo_id));
                    //return $db->query_first("SELECT geo_parent FROM geographic WHERE  geo_id = ".intval($rs1['geo_parent']));
                }
            }
            ?>
